﻿using AutoMapper;
using PagedList;
using SIG.Infrastructure.Configs;
using SIG.Infrastructure.Helper;
using SIG.InputModel.Admin.Articles;
using SIG.Model;
using SIG.Model.Case;
using SIG.Model.Enums;
using SIG.Resources.Admin;
using SIG.Service;
using SIG.Service.Case;
using SIG.ViewModel;
using SIG.ViewModel.Admin.Case;
using SIG.WebMVC.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using System.Xml.Linq;

namespace SIG.WebMVC.Areas.Admin.Controllers
{
    [SIGAuth]
    public class SolutionController : BaseController
    {
        private readonly ISolutionService _solutionService;
        private readonly IPageMetaService _pageMetaService;
        private readonly IMapper _mapper;

        public SolutionController(ISolutionService solutionService, IPageMetaService pageMetaService, IMapper mapper)
        {
            _solutionService = solutionService;
            _pageMetaService = pageMetaService;
            _mapper = mapper;

        }
        // GET: Admin/Solution

        #region Solution

        public ActionResult Index(int? page, string keyword)
        {
            SolutionListVM solutionListVM = GetElements(page, keyword);

            ViewBag.PageSizes = new SelectList(Site.PageSizes());
            return View(solutionListVM);

            //List<SolutionVM> vm = GetSolutionList();
            //return View(vm);
        }

        private SolutionListVM GetElements(int? page, string keyword)
        {
            var solutionListVM = new SolutionListVM();

            solutionListVM.Keyword = keyword;
            solutionListVM.PageIndex = (page ?? 1) - 1;
            solutionListVM.PageSize = SettingsManager.Case.PageSize;
            int totalCount;
            var solutionlist = _solutionService.GetPagedElements(solutionListVM.PageIndex, solutionListVM.PageSize, solutionListVM.Keyword, out totalCount);
            var solutionVMList = _mapper.Map<List<Solution>, List<SolutionVM>>(solutionlist);
            solutionListVM.TotalCount = totalCount;
            solutionListVM.Categories = new StaticPagedList<SolutionVM>(solutionVMList, solutionListVM.PageIndex + 1, solutionListVM.PageSize, solutionListVM.TotalCount); ;
            return solutionListVM;
        }

        [HttpPost]
        public JsonResult PageSizeSet(int pageSize)
        {
            try
            {
                var xmlFile = Server.MapPath("~/Config/CaseSettings.config");
                XDocument doc = XDocument.Load(xmlFile);

                var item = doc.Descendants("Settings").FirstOrDefault();
                item.Element("PageSize").SetValue(pageSize);
                doc.Save(xmlFile);

                return Json(AR, JsonRequestBehavior.DenyGet);
            }
            catch (Exception ex)
            {
                AR.Setfailure(ex.Message);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }
        }

        [HttpGet]
        public ActionResult Add()
        {
            var vSolution = new SolutionIM();
            vSolution.Active = true;
            vSolution.Importance = 0;

            return PartialView("_Add", vSolution);
        }



        [HttpPost]
        public JsonResult Add(SolutionIM vm)
        {

            if (!ModelState.IsValid)
            {
                AR.Setfailure(GetModelErrorMessage());
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

            var newSolution = _mapper.Map<SolutionIM, Solution>(vm);
            _solutionService.Create(newSolution);

            if (!string.IsNullOrEmpty(vm.Keywords) || !string.IsNullOrEmpty(vm.SEODescription))
            {
                var pageMeta = new PageMeta()
                {
                    ObjectId = newSolution.Id,
                    Keyword = vm.Keywords.Replace('，', ','),
                    Description = vm.SEODescription,
                    ModelType = ModelType.SOLUTION
                };
                _pageMetaService.Create(pageMeta);
            }

            int count;
            var pageSize = SettingsManager.Article.PageSize;
            var list = _solutionService.GetPagedElements(0, pageSize, string.Empty, out count);
            List<SolutionVM> categories = _mapper.Map<List<Solution>, List<SolutionVM>>(list);
            AR.Data = RenderPartialViewToString("_SolutionList", categories);

            AR.SetSuccess(String.Format(Messages.AlertCreateSuccess, EntityNames.Solution));
            return Json(AR, JsonRequestBehavior.DenyGet);

        }


        [HttpGet]
        public ActionResult Edit(int id)
        {

            Solution solution = _solutionService.GetById(id);
            if (solution == null)
            {
                AR.Setfailure(Messages.HttpNotFound);
                return Json(AR, JsonRequestBehavior.AllowGet);
            }

            var vm = _mapper.Map<SolutionIM>(solution);

            var pageMeta = _pageMetaService.GetPageMeta(ModelType.SOLUTION, solution.Id);
            if (pageMeta != null)
            {
                vm.Keywords = pageMeta.Keyword;
                vm.SEODescription = pageMeta.Description;
            }

            return PartialView("_Edit", vm);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]

        public JsonResult Edit(SolutionIM vm)
        {

            if (!ModelState.IsValid)
            {
                AR.Setfailure(GetModelErrorMessage());
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

            var newSolution = _mapper.Map<SolutionIM, Solution>(vm);
            _solutionService.Update(newSolution);

            var pageMeta = _pageMetaService.GetPageMeta(ModelType.SOLUTION, vm.Id);
            pageMeta = pageMeta ?? new PageMeta();


            if (!string.IsNullOrEmpty(vm.Keywords) || !string.IsNullOrEmpty(vm.SEODescription))
            {

                pageMeta.ObjectId = vm.Id;
                pageMeta.Keyword = vm.Keywords;
                pageMeta.Description = vm.SEODescription;
                pageMeta.ModelType = ModelType.SOLUTION;

                if (pageMeta.Id > 0)
                {
                    _pageMetaService.Update(pageMeta);
                }
                else
                {
                    _pageMetaService.Create(pageMeta);
                }
            }

            var solution = _mapper.Map<SolutionVM>(newSolution);
            AR.Id = solution.Id;
            AR.Data = RenderPartialViewToString("_SolutionItem", solution);

            AR.SetSuccess(String.Format(Messages.AlertUpdateSuccess, EntityNames.Solution));
            return Json(AR, JsonRequestBehavior.DenyGet);

        }

        // DELETE: /User/DeleteSite
        [HttpPost]
        [ValidateAntiForgeryToken]
        public JsonResult Delete(int id)
        {

            Solution vSolution = _solutionService.GetById(id);

            if (vSolution.Works.Any())
            {
                AR.Setfailure(string.Format(Messages.HasChildCanNotDelete, EntityNames.Solution, EntityNames.Work));
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

            _solutionService.Delete(vSolution);
            AR.SetSuccess(String.Format(Messages.AlertDeleteSuccess, EntityNames.Solution));
            return Json(AR, JsonRequestBehavior.DenyGet);

        }


        [HttpPost]
        [ValidateAntiForgeryToken]
        public JsonResult IsActive(int id)
        {

            var vSolution = _solutionService.GetById(id);
            if (vSolution == null)
            {
                AR.Setfailure(Messages.HttpNotFound);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

            try
            {
                vSolution.Active = !vSolution.Active;
                _solutionService.Update(vSolution);

                var vm = _mapper.Map<SolutionVM>(vSolution);

                AR.Data = RenderPartialViewToString("_SolutionItem", vm);
                AR.SetSuccess(String.Format(Messages.AlertUpdateSuccess, EntityNames.Solution));
                return Json(AR, JsonRequestBehavior.DenyGet);
            }
            catch (Exception ex)
            {
                AR.Setfailure(ex.Message);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }
        }


        //[AllowAnonymous]
        //public JsonResult IsSeoNameUnique(string seoName, int? Id)
        //{
        //    return !IsExist(seoName, Id)
        //        ? Json(true, JsonRequestBehavior.AllowGet)
        //        : Json(false, JsonRequestBehavior.AllowGet);
        //}
        //[AllowAnonymous]
        //public bool IsExist(string seoName, int? id)
        //{
        //    var wType = _solutionService.GetAll().Where(w => w.SeoName == seoName);
        //    if (id > 0)
        //    {
        //        wType = wType.Where(w => w.Id != id);
        //    }

        //    if (wType.Count() > 0)
        //        return true;

        //    return false;
        //}



        #endregion
    }
}